package com.bitejiuyeke.job_publish.controller;

import com.bitejiuyeke.job_publish.common.AppResult;
import com.bitejiuyeke.job_publish.common.PageResult;
import com.bitejiuyeke.job_publish.config.AppConfig;
import com.bitejiuyeke.job_publish.controller.params.FavoritePageByUserDTO;
import com.bitejiuyeke.job_publish.model.FavoriteRecord;
import com.bitejiuyeke.job_publish.service.IFavoriteRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.PositiveOrZero;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author 比特就业课
 */
// API描述
@Tag(name = "收藏职位相关接口")
// 日志
@Slf4j
// 校验
@Validated
// Controller注解，返回的对象用JSON形式表示
@RestController
// 路径映射
@RequestMapping("/favorite")
public class FavoriteRecordController {

    @Resource
    private IFavoriteRecordService service;

    @Operation(summary = "用户收藏职位")
    @PutMapping("/add/{jobId}")
    public AppResult addFavorite (HttpServletRequest request,
                                  @PositiveOrZero(message = "职位编号不正确") @PathVariable("jobId") Long jobId) {
        // 获取用户Id
        Long userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        // 调用Service
        FavoriteRecord record = new FavoriteRecord();
        record.setUserId(userId);
        record.setJobId(jobId);
        service.create(record);
        // 返回响应
        return AppResult.success();
    }

    @Operation(summary = "用户删除收藏")
    @DeleteMapping("/delete/{id}")
    public AppResult deleteFavorite (HttpServletRequest request,
                                     @PositiveOrZero(message = "参数不正确") @PathVariable("id") Long id) {
        // 获取用户Id
        Long userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        // 调用业务层
        service.deleteById(id, userId);
        // 返回响应
        return AppResult.success();
    }

    @Operation(summary = "根据用户信息查询OFFER记录")
    @GetMapping("/pageByUser")
    public AppResult<PageResult> selectPageByUser (HttpServletRequest request,
                                                   @Validated FavoritePageByUserDTO param) {
        Long userId = null;
        if (param.getUserId() == null) {
            userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        }
        // 获取当前用户
        param.setUserId(userId);
        // 条件对象
        FavoriteRecord favoriteRecord = new FavoriteRecord();
        BeanUtils.copyProperties(param, favoriteRecord);
        // 查询结果
        PageResult<FavoriteRecord> pageResult = service.selectPageByUser(favoriteRecord);
        // 返回
        return AppResult.success(pageResult);
    }
}
